import json
import os
from datetime import datetime
from flask import Blueprint, request, jsonify
from db import db1
from utils.data import get_data

bp_test = Blueprint('test', __name__)


@bp_test.route('/sendmoney')
def sendmoney():
    money = request.args.get('money')
    if not money:
        return jsonify({'code': 10011, 'mes': '必须输入金额'})
    else:
        try:
            money = float(money)
        except:
            return jsonify({'code': 10012, 'mes': '格式错误'})

    if money < 200 and money > 0.01:
        return jsonify({'code': 200, 'mes': '格式正确'})
    else:
        return jsonify({'code': 10010, 'mes': '金额不允许'})


@bp_test.route('/sendredbag', methods=['POST'])
def sendredbag():
    data = get_data()
    sql = "insert into redbag(name,url,method,params,result) values('%s','%s','%s',%s,'%s')" % (
        data['name'], data['url'], data['method'], data['params'], data['result'])
    db1.insert(sql)
    return jsonify({"code": 200})


import requests


@bp_test.route('/test_sendMoney')
def test_sendMoney():
    # 读取数据库
    sql = "select * from test_record where status=1"
    res = db1.findall(sql)
    list = []
    for i in res:
        flag = "失败"
        params = json.loads(i['params'])
        if i['method'] == "get":
            mes = requests.get(i['url'], params=params)
        elif i['method'] == "post":
            mes = requests.post(i['url'], data=params)
        mm = json.loads(mes.text)
        if mm['code'] == int(i['result']):
            flag = '成功'
        str = {"name": i['name'], "请求地址": i['url'], "返回信息": mes.text, "测试结果": flag}
        list.append(str)
        filename = datetime.datetime.strftime(datetime.datetime.now(), '%Y%m%d')
        with open(os.path.join('./logs/' + filename + '.txt'), 'w') as f:
            f.write(json.dumps(list, ensure_ascii=False))

    return jsonify({"code": 200})
